package com.itcam.wemedia.service.impl;

import com.itcam.apis.article.IArticleClient;
import com.itcam.apis.user.IUserClient;
import com.itcam.model.common.dtos.CommentConfigDto;
import com.itcam.model.common.dtos.CommentRepaySaveDto;
import com.itcam.model.common.dtos.ResponseResult;
import com.itcam.model.common.enums.AppHttpCodeEnum;
import com.itcam.model.common.pojos.ApComment;
import com.itcam.model.common.pojos.ApCommentLike;
import com.itcam.model.common.pojos.ApCommentRepay;
import com.itcam.model.common.pojos.ApCommentRepayLike;
import com.itcam.model.user.pojos.ApUser;
import com.itcam.model.wemedia.pojos.WmUser;
import com.itcam.utils.thread.WmThreadLocalUtil;
import com.itcam.wemedia.mapper.WmUserMapper;
import com.itcam.wemedia.service.CommentManageService;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.checkerframework.checker.units.qual.A;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author : Cammy.Wu
 * Description : 
 */

@Service
@Slf4j
public class CommentManageServiceImpl implements CommentManageService {

    @Autowired
    private MongoTemplate mongoTemplate;

    @Autowired
    private WmUserMapper wmUserMapper;

    @Autowired
    private IUserClient userClient;

    @Autowired
    private IArticleClient artcleClient;

    /**
     * 删除评论
     * @param commentId
     * @return
     */
    @Override
    public ResponseResult delComment(String commentId) {
        if (StringUtils.isBlank(commentId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论id不能为空");
        }
        //删除评论
        mongoTemplate.remove(Query.query(Criteria.where("id").is(commentId)), ApComment.class);
        //删除该评论的所有的回复内容
        mongoTemplate.remove(Query.query(Criteria.where("commentId").is(commentId)), ApCommentRepay.class);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 删除评论回复
     * @param commentRepayId
     * @return
     */
    @Override
    public ResponseResult delCommentRepay(String commentRepayId) {
        // 检查传入的评论回复ID是否为空，如果为空则返回错误信息
        if (StringUtils.isNotBlank(commentRepayId)) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论回复id不能为空");
        }
        // 创建一个查询对象，用于查询ID等于传入的评论回复ID的评论回复记录
        Query query = Query.query(Criteria.where("id").is(commentRepayId));
        // 使用MongoTemplate的remove方法删除符合查询条件的评论回复记录
        mongoTemplate.remove(query, ApCommentRepay.class);
        // 返回操作成功的信息
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);

    }

    /**
     * 回复评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult saveCommentRepay(CommentRepaySaveDto dto) {
        // 1.检查参数
        if (dto == null || StringUtils.isBlank(dto.getContent()) || dto.getCommentId() == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID);
        }
        if (dto.getContent().length() > 140) {
            return ResponseResult.errorResult(AppHttpCodeEnum.PARAM_INVALID, "评论内容不能超过140字");
        }
        // todo:2.安全检查
        //获取自媒体人信息
        WmUser wmUser = WmThreadLocalUtil.getUser();
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        if (dbUser == null) {
            return ResponseResult.errorResult(AppHttpCodeEnum.NEED_LOGIN);
        }
        //获取app端用户信息
        ApUser apUser = userClient.findUserById(dbUser.getApUserId());
        //3.保存评论
        ApCommentRepay apCommentRepay = new ApCommentRepay();
        apCommentRepay.setAuthorId(apUser.getId());
        apCommentRepay.setAuthorName(apUser.getName());
        apCommentRepay.setContent(dto.getContent());
        apCommentRepay.setCreatedTime(new Date());
        apCommentRepay.setCommentId(dto.getCommentId());
        apCommentRepay.setUpdatedTime(new Date());
        apCommentRepay.setLikes(0);
        mongoTemplate.save(apCommentRepay);
        // 4.更新回复数量
        ApComment apComment = mongoTemplate.findById(dto.getCommentId(), ApComment.class);
        apComment.setReply(apComment.getReply() + 1);
        mongoTemplate.save(apComment);
        return ResponseResult.okResult(AppHttpCodeEnum.SUCCESS);
    }

    /**
     * 打开或关闭评论
     * @param dto
     * @return
     */
    @Override
    public ResponseResult updateCommentStatus(CommentConfigDto dto) {
        // 1.获取当前用户
        WmUser wmUser = WmThreadLocalUtil.getUser();
        // 2.app端用户id
        WmUser dbUser = wmUserMapper.selectById(wmUser.getId());
        Integer apUserId = dbUser.getApUserId();
        // 3.清空该文章的所有评论
        Query query = Query.query(Criteria.where("articleId").is(dto.getArticleId()).and("authorId").is(apUserId));
        List<ApComment> apCommentList = mongoTemplate.find(query, ApComment.class);
        for (ApComment apComment : apCommentList) {
            Query queried = Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId));
            List<ApCommentRepay> commentRepayList = mongoTemplate.find(queried, ApCommentRepay.class);
            List<String> commentRepayIdList = commentRepayList.stream().map(ApCommentRepay::getId).distinct().collect(Collectors.toList());
            // 删除所有的评论回复点赞数量
            mongoTemplate.remove(Query.query(Criteria.where("commentRepayId").in(commentRepayIdList).and("authorId").is(apUserId)), ApCommentRepayLike.class);
            // 删除该评论的所有回复内容
            mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId)), ApCommentRepay.class);
            // 删除评论的点赞
            mongoTemplate.remove(Query.query(Criteria.where("commentId").is(apComment.getId()).and("authorId").is(apUserId)), ApCommentLike.class);
        }
        // 删除评论
        mongoTemplate.remove(Query.query(Criteria.where("entryId").is(dto.getArticleId()).and("authorId").is(apUserId)),ApComment.class);
        // 修改app文章的config配置
        return artcleClient.updateCommentStatus(dto);
    }
}
